import threading
import gtk

total_threads_max=20

def _get_list_from_stock_data(sd):
    dl=[sd.code,sd.name,sd.change_percent,sd.price_now]
    dl=dl+[sd.change,sd.price_lastday,sd.price_today_start]
    dl=dl+[sd.price_highest,sd.price_lowest,sd.price_bid_buy]
    dl=dl+[sd.price_bid_sale,sd.amount/100.0]#,sd.amount_money]
    return dl

def update_liststore(listview,stock_quotation_list):
    update_liststore_1(listview,stock_quotation_list)
    
def update_liststore_1(listview,stock_quotation_list):
    sdl=[]
    for sd in stock_quotation_list:
        dl=_get_list_from_stock_data(sd)
        sdl.append(dl)
    gtk.gdk.threads_enter
    try:
        model=listview.get_model()
        sel=listview.get_selection()
        (model, iter) = sel.get_selected()
        if(iter<>None): scode=model.get_value(iter,0)
        else: scode=None
        model.clear()
        for x in sdl:
            iter=model.append(x)
            if(scode<>None and x[0]==scode):
                sel=listview.get_selection()
                sel.select_iter(iter)
                scode==None
    finally:gtk.gdk.threads_leave()
        

def update_liststore_2(model,stock_quotation_list):
    ms=len(model)
    sd_map={}
    for sd in stock_quotation_list:
        dl=_get_list_from_stock_data(sd)
        #[sd.code,sd.name,sd.change_percent,sd.price_now,
        #sd.change,sd.price_lastday,sd.price_today_start,
        #sd.price_highest,sd.price_lowest,sd.price_bid_buy,
        #sd.price_bid_sale,sd.amount,sd.amount_money]
        sd_map[dl[0]]=dl
    to_remove_list=[]
    gtk.gdk.threads_enter()
    try:
        for i in range(0,ms):
            ir=model.get_iter((i,))
            code=model.get_value(ir,0)
            if(sd_map.has_key(code)):
                dl=sd_map.pop(code)
                for j in range(0,len(model[i])):
                    model.set_value(ir,j,dl[j])
            else:
                to_remove_list.append((i,))
        for path in to_remove_list:model.remove(model.get_iter(path))
        for i in sd_map.values():model.append(i)
    finally:
        gtk.gdk.threads_leave()

def create_thread(func,name=None,run=True,args=(),kwargs={}):
    global total_threads_max
    if(threading.activeCount()>total_threads_max):
        print "ERROR:total active threads (%d) > max (%d)",(threading.activeCount(),total_threads_max)
        return None
    th=threading.Thread(None,func,name,args,kwargs)
    if(run):th.start()
    return th
    
def create_timer(interval,func,run=True,args=(),kwargs={}):
    if(threading.activeCount()>total_threads_max):
        print "ERROR:total active threads (%d) > max (%d)",(threading.activeCount(),total_threads_max)
        return None
    th=threading.Timer(interval,func,args,kwargs)
    if(run):th.start()
    return th
    
